import router from './router';
import store from './store';
import { Message } from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';// progress bar style
import { getToken } from '@/utils/auth'; // getToken from cookie

NProgress.configure({ showSpinner: false });// NProgress Configuration

// permissiom judge function
function hasPermission(roles, permissionRoles) {
    if (roles.indexOf('admin') >= 0) return true; // admin permission passed directly
    if (!permissionRoles) return true;
    return roles.some(role => permissionRoles.indexOf(role) >= 0);
}

const whiteList = ['/login', '/authredirect', '/404', '/401'];// no redirect whitelist

router.beforeEach((to, from, next) => {
    NProgress.start(); // start progress bar
    // 前端页面不需要权限, 在免登录白名单，直接进入
    if (whiteList.indexOf(to.path) !== -1 || to.path.startsWith('/f')) {
        // check login state
        if (getToken()) {
            store.dispatch('GetUserInfo').then().catch();
        }
        next();
        NProgress.done();
        return;
    }
    // enter pages that need user logon
    if (getToken()) {

        if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
            store.dispatch('GetUserInfo').then(data => { // 拉取user_info
                // 管理员才能进后台
                if (data.user.type === store.state.userType.admin) {
                    next('/a');
                } else {
                    next('/u/user');
                }
                const roles = data.user.roles; // note: roles must be a array! such as: ['editor','develop']
                store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
                    router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
                    next({ ...to, replace: true }); // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                });
            }).catch(() => {
                store.dispatch('FedLogOut').then(() => {
                    Message.error('太久时间没登录，请重新登录');
                    next({ path: '/f/login' });
                });
            });
        } else {
            if (to.path.startsWith('/u')) {
                next();
                return;
            }
            // 管理员才能进后台
            // 没有动态改变权限的需求可直接next() 删除下方权限判断
            if (to.path.startsWith('/a') && store.state.user.info.type === store.state.userType.admin && hasPermission(store.getters.roles, to.meta.roles)) {
                store.dispatch('GenerateRoutes', { roles: store.getters.roles })
                    .then(() => { // 根据roles权限生成可访问的路由表
                        router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
                        next();//
                    });
            } else {
                next({ path: '/401', replace: true, query: { noGoBack: true }});
            }
        }
    } else {
        next('/f/login');
        NProgress.done();
    }
});

router.afterEach(() => {
    NProgress.done(); // finish progress bar
});
